package br.com.rapidrest.chain;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

import br.com.rapidrest.exception.BindingException;
import br.com.rapidrest.exception.ChainException;

public class ELBindingCommand implements Command {

	private static final Pattern NAME_PATTERN = Pattern.compile("^\\$\\{(.+)\\}$");

	@Override
	@SuppressWarnings("unchecked")
	public void execute(Chain chain) throws ChainException {
		BasicChainContext context = (BasicChainContext) chain.getContext();
		HttpServletRequest request = context.getRequest();
		Map parameterMap = request.getParameterMap();
		bind(parameterMap, context.getBean());
		chain.proceed();
	}

	public void bind(Map<String, String[]> params, Object bean)
			throws BindingException {
		for (Entry<String, String[]> entry : params.entrySet()) {
			String key = entry.getKey().trim();
			Matcher matcher = NAME_PATTERN.matcher(key);
			if (matcher.matches()) {
				key = matcher.group(1);
				Object value = entry.getValue();
				try {
					BeanUtils.setProperty(bean, key, value);
				} catch (IllegalAccessException e) {
					throw new BindingException(e);
				} catch (InvocationTargetException e) {
					throw new BindingException(e);
				}
			}
		}
	}

}
